package cn.qdhlm.access.preview;

import com.healthmarketscience.jackcess.*;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

public class ReadAccess {
    public static void main(String[] args) {
//        Timer timer = new Timer();
//        timer.schedule(new TimerTask() {
//            @Override
//            public void run() {
        Database database = openDB();

        read(database);
//            }
//        }, 0, 5000);
    }

    private static Database openDB() {
        Database database = null;
        try {
            database = DatabaseBuilder.open(new File("D:\\workspace\\access\\20200812001.mdb"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return database;
    }

    private static void read(Database database) {
        try {
            Set<String> tableNames = database.getTableNames();
            tableNames.forEach((tableName) -> {
                System.out.println("read tableName: " + tableName + " start...");
                read(database, tableName);
                System.out.println("read tableName: " + tableName + " end...");
                System.out.println();
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void read(Database database, String tableName) {
        Table table = null;
        try {
            table = database.getTable(tableName);
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (null != table) {
            List<? extends Column> columns = table.getColumns();
            for(Column column: columns) {
                System.out.print(column.getName());
                System.out.print(";");
            }
            for (Row row : table) {
                for (Column column : columns) {
                    System.out.print(row.get(column.getName()));
                    System.out.print(";");
                }
                System.out.println();
            }
            System.out.println("rowCount:" + table.getRowCount());
        }
    }
}
